package com.yanx.common.page.cursor;

import com.yanx.common.page.PageConstant;
import com.yanx.common.page.PageHelper;
import com.yanx.common.page.PageVo;
import com.yanx.common.utils.ThreadLocal_;
import com.yanx.common.utils.Url_;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;

import java.util.Map;

@Getter
@Setter
public class CursorPageVo extends PageVo {
    private Boolean hasNext;
    private Cursor cursor;
    private Link link;
    private Integer total;

    public CursorPageVo() {
        this.setHasNext(ThreadLocal_.get(PageConstant.CURSOR_HASNEXT));
        this.setCursor(new Cursor());
        this.setLink(new Link());
        this.setTotal(ThreadLocal_.get(PageConstant.TOTAL_NUMBER));
    }

    @Data
    class Cursor {
        private String before;
        private String after;

        public Cursor() {
            this.before = ThreadLocal_.get(PageConstant.CURSOR_BEFORE);
            this.after = ThreadLocal_.get(PageConstant.CURSOR_AFTER);
        }
    }

    @Data
    class Link {
        private String current;
        private String previous;
        private String next;

        public Link() {
            String currentLink = ThreadLocal_.get(PageConstant.CURSOR_LINK);
            Map<String, String> queryMap = Url_.splitQuery(currentLink);
            //current
            this.current = currentLink;

            //先删去参数，然后再重新添加
            currentLink = Url_.removeParams(currentLink, "limit", "before", "after");
            //limit
            String limit = queryMap.get("limit");
            if (limit == null) {
                currentLink = Url_.appendParam(currentLink, "limit", PageHelper.Cursor.getLimit() + "");
            }
            //previous
            this.previous = Url_.appendParam(currentLink, "before", ThreadLocal_.get(PageConstant.CURSOR_BEFORE));
            //next
            this.next = Url_.appendParam(currentLink, "after", ThreadLocal_.get(PageConstant.CURSOR_AFTER));

        }
    }
}
